package edu.nus.mtech.sem1.ca.main;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import edu.nus.mtech.sem1.ca.cust.Customer;
import edu.nus.mtech.sem1.ca.exception.CustomerNotFoundException;
import edu.nus.mtech.sem1.ca.main.dao.TelephonyApplicationDao;
import edu.nus.mtech.sem1.ca.utils.Common;
import edu.nus.mtech.sem1.ca.utils.Logger;
import edu.nus.mtech.sem1.ca.utils.TelephonyConstants;

/**
 * List window which wraps the Complaints JTable. Looks really awesome !!!
 *
 */
public class FormAllCustomers extends JInternalFrame {
	private JTable table;
	private JTextField textField;
	private TelephonyApplicationDao telephoneDao=new TelephonyApplicationDao();

	private JTextField txtSearchInput;
	private ArrayList<Customer> l_cusArray;
	private Vector<Customer> columnHeader;
	private Vector<String> columnData;
	private JLabel messageLabel; 
	/**
	 * Create the panel.
	 */
	public FormAllCustomers() {
		setTitle("Customer Search");
		setClosable(true);
		setBounds(100, 100, 907, 494);
		getContentPane().setLayout(null);
		
		JLabel lblSearchBy = new JLabel("Search By NRIC");
		lblSearchBy.setBounds(11, 15, 135, 14);
		getContentPane().add(lblSearchBy);
		
		txtSearchInput = new JTextField();
		txtSearchInput.setBounds(200, 10, 164, 20);
		txtSearchInput.setToolTipText("Clear text box for full search");
		getContentPane().add(txtSearchInput);
		txtSearchInput.setColumns(50);
		
		
		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				if (txtSearchInput.getText()!=null){
					try {
						Set<Customer> customers=searchCustomer(txtSearchInput.getText().toUpperCase());
						Vector columnHeader=getColumnHeaderForCustomer();
						Vector columnData=getColumnDataFromCustomerObjects(customers);
//						table = new JTable(columnData, columnHeader);
//						table.setBounds(11, 43, 869, 379);
						table.setModel(new TelephonyJTableModel(columnHeader, columnData));
					} catch (CustomerNotFoundException e) {
						e.printStackTrace();
					}
				}
				
			}
		});
		btnSearch.setBounds(418, 12, 89, 23);
		getContentPane().add(btnSearch);
		
		//LoadCustomers();
		Set<Customer> allCustomers=null;
		try {
			allCustomers = telephoneDao.retrieveAllCustomers();
		} catch (CustomerNotFoundException e) {
			e.printStackTrace();
		}
		Vector columnHeader=getColumnHeaderForCustomer();
		Vector columnData=getColumnDataFromCustomerObjects(allCustomers);
		Logger.log("column header : "+columnHeader);
		Logger.log("column data: "+columnData);
		TelephonyJTableModel customerTableModel = new TelephonyJTableModel(columnHeader, columnData);
		table = new JTable(customerTableModel);
		
		//getContentPane().add(table);
		
		JButton btnSelect = new JButton("View Customer");
		btnSelect.setBounds(11, 431, 179, 23);
		getContentPane().add(btnSelect);
		
		btnSelect.addActionListener(new CustomerSelectActionListener());
		
		DefaultTableModel headerData = new DefaultTableModel(0, 1);
		headerData.addRow(columnHeader.toArray()); 
        JTable rowHeader = new JTable(new DefaultTableModel(
        	new Object[][] {
        	},
        	new String[] {
        	}
        ));

      /*  LookAndFeel.installColorsAndFont
            (rowHeader, "TableHeader.background", 
            "TableHeader.foreground", "TableHeader.font");
*/
        
        rowHeader.setIntercellSpacing(new Dimension(0, 0));
        Dimension d = rowHeader.getPreferredScrollableViewportSize();
        d.width = rowHeader.getPreferredSize().width;
        rowHeader.setPreferredScrollableViewportSize(d);
        rowHeader.setRowHeight(table.getRowHeight());
        
        JScrollPane scrollPane = new JScrollPane(table);
        
        scrollPane.setRowHeaderView(rowHeader);

        JTableHeader corner = rowHeader.getTableHeader();
        corner.setReorderingAllowed(false);
        corner.setResizingAllowed(false);

        scrollPane.setBounds(11, 43, 869, 379);
        scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, corner);
        scrollPane.setVisible(true);


        getContentPane().add(scrollPane, BorderLayout.CENTER);
        
        messageLabel = new JLabel("");
        messageLabel.setBounds(537, 15, 343, 20);
        getContentPane().add(messageLabel);
        
        JButton btnViewComplaints = new JButton("View Complaints");
        btnViewComplaints.addActionListener(new ComplaintsSelectActionListener());
        btnViewComplaints.setBounds(230, 431, 164, 23);
        getContentPane().add(btnViewComplaints);

		
		
		
		
//	    SelectionListener listener = new SelectionListener(table);
//	    table.getSelectionModel().addListSelectionListener(listener);
//	    table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
		

	}


	/**
	 * Returns the header for the JTable
	 * @param headerCustomer
	 * @return
	 */
	private Vector<String> getColumnHeaderForCustomer() {
		Vector<String> headerList=new Vector<String>();
		//Ah. just for a change. let's use a tokenizer
		StringTokenizer tokenizer=new StringTokenizer(TelephonyConstants.HEADER_CUSTOMER, TelephonyConstants.SEMICOLON);
		
		for(String tempString; tokenizer.hasMoreTokens();){
			tempString=tokenizer.nextToken();
			headerList.add(tempString);
		}
		Logger.log("Header list "+headerList);
		return headerList;
	}
		
	private Vector<Vector> getColumnDataFromCustomerObjects(Set<Customer> customers) {
		
		Vector<Vector> columnData=new Vector<Vector>();
		Vector<String> eachColumnData=null;
		
		for (Customer eachCustomer:customers){
			
			if (eachCustomer!=null){
				eachColumnData=new Vector<String>();
				//nric
				eachColumnData.add(eachCustomer.getNric());
				//name
				eachColumnData.add(eachCustomer.getName());
				//address
				eachColumnData.add(eachCustomer.getAddress());
				//interests
				eachColumnData.add(eachCustomer.getInterests());
				//email
				eachColumnData.add(eachCustomer.getEmail());
				//status
				eachColumnData.add(eachCustomer.getStatus().toString());
				//accountnumber
				eachColumnData.add(eachCustomer.getAccountNo());
				
				columnData.add(eachColumnData);
				Logger.log("column data "+columnData);
			}
			
		}
		
		return columnData;
	}
	

	private Set<Customer> searchCustomer(String nric) throws CustomerNotFoundException {
		Set<Customer> customers =new HashSet<Customer>();
		try {
			if (nric==null || nric.trim().equals("")){
				customers=telephoneDao.retrieveAllCustomers();
			}
			else{
				Customer customer = telephoneDao.retrieveCustomerData(nric);
				customers.add(customer);
			}
		} catch (CustomerNotFoundException e) {
			messageLabel.setText(TelephonyConstants.ERR_CUSTOMER_NOT_FOUND);
			throw e;
		}
		return customers;
	}

	
	private class CustomerSelectActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent actionEvent) {

				 //JTable jtable = (JTable) mouseEvent.getSource();
			     int selection= table.getSelectedRow();
			     Logger.log("Selected row "+selection);
			     table.clearSelection();
			     try {
					Logger.log(table.getModel().getValueAt(selection, 0));
					 
					 String nric=(String) table.getModel().getValueAt(selection, 0);
					 //String name=(String) table.getModel().getValueAt(selection, 1);
					 
					 setVisible(false);
					 Customer customer = telephoneDao.retrieveCustomerData(nric);
					 FormCustomer frmCustomerObj=new FormCustomer(customer);
					 //to prevent from opening multiple windows.
					 for (java.awt.Component var : getParent().getComponents()) {
						if(var instanceof FormCustomer){
							var.setVisible(false);
							if(var instanceof JInternalFrame){
								((JInternalFrame)var).dispose();
							}
						}
					}
					 //to prevent from opening multiple windows.
					 getParent().add(frmCustomerObj);
					 Common.OpenCenterScreen(frmCustomerObj, true);					
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, TelephonyConstants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
					//e.printStackTrace();
				}				
				finally{
					//clear the memory of this object.
					dispose();
				}
		}
		
	}
	
	private class ComplaintsSelectActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent actionEvent) {

				 //JTable jtable = (JTable) mouseEvent.getSource();
			     int selection= table.getSelectedRow();
			     Logger.log("Selected row "+selection);
			     table.clearSelection();

			     
			     try {
					Logger.log(table.getModel().getValueAt(selection, 0));
					 String nric=(String) table.getModel().getValueAt(selection, 0);
					 String name=(String) table.getModel().getValueAt(selection, 1);
					 
					 setVisible(false);
					 FormAllComplaints frmComplaintObj=new FormAllComplaints(nric,name );
					 getParent().add(frmComplaintObj);
					 Common.OpenCenterScreen(frmComplaintObj, true);
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, TelephonyConstants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
					//e.printStackTrace();
				}
		}
		
	}
}
